package com.thb.pay.core.utils;

import java.util.HashMap;
import java.util.Map;

public class ContextHolder {


    public static final String KEY_TENANT_ID = "tenantId";

    public static final String KEY_USER_ID = "userId";


    public static final String KEY_APPID_KEY = "appId";

    private static final ThreadLocal<Map<String, Object>> THREAD_LOCAL_CONTEXTS = new ThreadLocal<>();

    public static Map<String, Object> currentContextMap() {
        Map<String, Object> context = THREAD_LOCAL_CONTEXTS.get();

        if (context == null) {
            context = initContextMap();
        }
        return context;
    }

    protected static Map<String, Object> initContextMap() {
        Map<String, Object> context = new HashMap<>();
        THREAD_LOCAL_CONTEXTS.set(context);
        return context;
    }

    protected static boolean has(String key) {
        return currentContextMap().containsKey(key);
    }

    protected static <T> T get(String key, Class<T> valueClass) {
        Map<String, Object> currentContextMap = currentContextMap();
        if (currentContextMap.containsKey(key)) {
            Object o = currentContextMap.get(key);
            if (valueClass.isInstance(o)) {
                return valueClass.cast(o);
            }
        }
        return null;
    }

    protected static <T> void set(String key, T value) {
        Map<String, Object> context = currentContextMap();
        if (context.containsKey(key)) {
            context.remove(key);
        }

        context.put(key, value);
    }

    protected static void delete(String key) {
        Map<String, Object> currentContextMap = currentContextMap();
        if (currentContextMap.containsKey(key))
            currentContextMap.remove(key);
    }

    public static void removeCurrentContextMap() {
        THREAD_LOCAL_CONTEXTS.remove();
    }

    public static Long getTenantId() {
        Long currentTenantId = get(KEY_TENANT_ID, Long.class);
        return currentTenantId;
    }

    public static boolean existTenantId() {
        return has(KEY_TENANT_ID);
    }

    public static void setTenantId(Long tenantId) {
        set(KEY_TENANT_ID, tenantId);
    }

    public static void removeTenantId() {
        delete(KEY_TENANT_ID);
    }

    public static Long getUserId() {
        return get(KEY_USER_ID, Long.class);
    }

    public static boolean existUserId() {
        return has(KEY_TENANT_ID);
    }

    public static void setUserId(Long userId) {
        set(KEY_USER_ID, userId);
    }

    public static void removeUserId() {
        delete(KEY_USER_ID);
    }


    public static void setAppId(String appId) {
        set(KEY_APPID_KEY, appId);
    }

    public static String getAppId() {
        return get(KEY_APPID_KEY, String.class);
    }

    public static void removeAppId() {
        delete(KEY_APPID_KEY);
    }
}
